package demo1;
/*
组合设计模式：将对象组合成树形结构以表示部分整体的层次结构。组合模式使得用户对单个对象
和组合对象的使用具有一致性
 */

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite composite = new Composite("Composite X");
        composite.Add(new Leaf("Leaf XA"));
        composite.Add(new Leaf("Leaf XB"));

        root.Add(composite);

        root.Display();

    }
}

//Component 为组合中的对象声明接口,在适当情况下,实现所有类共同接口的默认,声明一个接口用于访问和管理Component的子部件

abstract class Component{
    protected  String  name ;

    public Component(String name){
        this.name = name;
    }
    public abstract void Add(Component c);
    public abstract void Remove(Component c);
    public abstract void Display();
}

class Leaf extends Component{
    //Leaf在组合中表示叶节点对象，叶节点没有子节点


    public Leaf(String name) {
        super(name);
    }

    @Override
    public void Add(Component c) {
        System.out.println("不能添加,已经是叶子节点");
    }

    @Override
    public void Remove(Component c) {
        System.out.println("不能删除,已经是叶子节点");
    }

    @Override
    public void Display() {
        System.out.println("叶子：" +name);
    }
}

class Composite extends Component{

    private List<Component>children = new ArrayList<Component>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void Add(Component c) {
        children.add(c);
    }

    @Override
    public void Remove(Component c) {
        children.remove(c);
    }

    @Override
    public void Display() {
        System.out.println("枝干 "+name);
        for (Component component:children
             ) {
            component.Display();
        }
    }
}